<template>
  <div class="upload-module">
    <div
      class="operation"
      :class="{ active: dragActive }"
      droppable
      @dragover.prevent="handleDragover"
      @dragleave="handleDragleave"
      @drop.prevent="handleDrop"
      @dragenter="handleDragenter"
      @click="handleClick"
    >
      <i class="icon">
        <el-icon><Files /></el-icon>
      </i>
      <span class="text">{{ tipText }}</span>
    </div>
  </div>
</template>

<script lang="ts" setup>
import useGlobalLoadingStateStroe from '@renderer/store/Loading/GlobalLoadingStateStroe'
import { Files } from '@element-plus/icons-vue'
import { ref, computed } from 'vue'

const props = defineProps<{
  // 文件 / 目录标志
  flag: 'file' | 'folder'
}>()

const emits = defineEmits(['change'])

const loadingStateStroe = useGlobalLoadingStateStroe()

const tipText = computed(() =>
  props.flag === 'file'
    ? '点击添加 / 拖拽文件到此区域'
    : '点击添加 / 拖拽文件夹到此区域'
)

const dragActive = ref(false)

function handleDrop(event: DragEvent) {
  dragActive.value = false

  loadingStateStroe.parseFile(() => {
    if (event.dataTransfer && event.dataTransfer.files) {
      const files = Array.from(event.dataTransfer.files)
      // 过滤出所有的路径
      const paths = files.map((item) => item.path)
      emits('change', paths)
    }
  })
}

function handleDragover(event: DragEvent) {
  if (event) {
    // 更改鼠标指针
    event.dataTransfer!.dropEffect = 'copy'
  }
}

function handleDragleave() {
  dragActive.value = false
}

function handleDragenter() {
  dragActive.value = true
}

async function handleClick() {
  let filePaths: string[]

  if (props.flag === 'file') {
    filePaths = await window.api.selectMultiFile()
  } else {
    filePaths = await window.api.selectMultiFolder()
  }

  if (filePaths.length > 0) {
    loadingStateStroe.parseFile(() => {
      emits('change', filePaths)
    })
  }
}
</script>

<style lang="less" scoped>
.upload-module {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: var(--el-text-color-placeholder);

  .operation {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 1px dashed var(--el-color-primary-light-5);
    margin: 0 60px 30px;
    min-width: 360px;
    max-width: 570px;
    box-sizing: border-box;
    height: 285px;
    border-radius: 6px;
    background: var(--el-fill-color-blank);
    cursor: pointer;

    .icon {
      margin-bottom: 8px;
      font-size: 68px;
      color: var(--el-color-primary-light-3);
    }

    .text {
      color: var(--el-color-primary-light-3);
    }

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}
</style>
